package com.sora.user.service.impl;

import com.sora.basic.exception.BusinessException;
import com.sora.basic.util.Md5Utils;
import com.sora.basic.util.StrUtils;
import com.sora.org.domain.Employee;
import com.sora.org.domain.Shop;
import com.sora.user.domain.Logininfo;
import com.sora.user.domain.User;
import com.sora.user.mapper.LogininfoMapper;
import com.sora.user.mapper.UserMapper;
import com.sora.user.service.IUserService;
import com.sora.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;


    @Override
    public void phoneRegister(Map<String, String> map) {
        //校验空值
        /*phoneUserForm: {
            imageCode: "", phone: '15181145237', phoneCode:'', password:'', confirmPassword:''
        }*/
        if(StringUtils.isEmpty(map.get("phone")) || StringUtils.isEmpty(map.get("phoneCode")) ||
                StringUtils.isEmpty(map.get("password")) || StringUtils.isEmpty(map.get("confirmPassword"))){
            throw new BusinessException("注册的信息不能为空！！！");
        }

        //判断两次输入的密码是否一致
        if(!map.get("password").equals(map.get("confirmPassword"))){
            throw new BusinessException("两次输入的密码不一致！！！");
        }

        //判断验证码是否过期，用户输入的验证码是否一致
        //判断验证码是否过期【key,value】--> 【业务键:手机号码 , 验证码:时间戳】
        Object val = redisTemplate.opsForValue().get("register:" + map.get("phone"));
        if(val == null){
            throw new BusinessException("验证码已经过期了，请重新获取！！！");
        }

        //判断用户输入的验证码是否一致
        if(!map.get("phoneCode").equals(val.toString().split(":")[0])){
            throw new BusinessException("两次输入的验证码不一致！！！");
        }


        //二、添加到数据库
        //当将一个对象转换成另一个对象的时候，而且代码量多的时候就用obj2Obj
        //将map的值转为User对象
        User user = map2User(map);
        /*//将user对象转为Logininfo对象，同步信息到t_logininfo
        Logininfo logininfo = user2Logininfo(user);
        //先添加logininfo到t_logininfo，生成自增长id
        logininfoMapper.save(logininfo);

        //将Logininfo自增长id设置到user中去
        user.setLogininfoId(logininfo.getId());*/
        //再添加user到t_user中去
        save(user);

    }

    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        //一、校验空值，两次输入的密码是否一致
        //1、校验空值
        /*email:'',password:'',passwordRepeat:'',*/
        if(map.get("email") == null || map.get("password") == null || map.get("passwordRepeat") == null){
            throw new BusinessException("用户注册的信息不能为空！！！");
        }
        //2、两次输入的密码是否一致
        if(!map.get("password").equals(map.get("passwordRepeat"))){
            throw new BusinessException("两次输入的密码不一致！！！");
        }

        //二、校验通过之后，将用户信息保存在数据库中，并将用户的状态改为待激活
        User user = map2User(map);
        /*Logininfo logininfo = user2Logininfo(user);
        //添加之后生成自增长id
        logininfoMapper.save(logininfo);

        //将t_logininfo表生成的自增长id设置到user的logininfo_id字段
        user.setLogininfoId(logininfo.getId());*/
        //将user的state修改为0表示禁用，点击邮件激活之后改为1，表示激活
        user.setState(0);
        //将user保存到数据库
        save(user);


        //三、发送邮件激活
        //发送邮件点击激活注册
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1203269902@qq.com");
        helper.setSubject("邮箱注册激活邮件");

        String email = map.get("email");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>邮箱注册激活邮件!!!</h1><a href='http://127.0.0.1:8080/user/email/active/?email="+email+"'>点击该链接激活</a>",true);
        //添加附件
        helper.addAttachment("p24.jpg",new File("D:\\javastudy\\课堂代码\\03_images\\项目二宠物图片\\p24.jpg"));

        //收件人
        helper.setTo(map.get("email"));
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void emailActive(Integer state,String email) {
        userMapper.updateState(1,email);
    }

    /*private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //调研工具类克隆属性
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//type = 1表示用户
        logininfo.setDisable(true);//设置状态为启用
        return logininfo;
    }*/

    private User map2User(Map<String, String> map) {
        User user = new User();
        if(map.get("phone") != null){
            //通过手机号注册的用户
            user.setUsername(map.get("phone"));
        }else {
            //通过邮箱注册的用户
            user.setUsername(map.get("email"));
        }

        user.setPhone(map.get("phone"));
        user.setEmail(map.get("email"));


        /*//获取随机生成的盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //用Md5Utils工具类生成加密加盐的密码
        String password = Md5Utils.encrypByMd5(map.get("password") + salt);
        user.setPassword(password);*/

        //手机注册的用户默认启用
        user.setState(1);
        return user;
    }

    @Override
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    @Override
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.loadById(id);

        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());

        super.del(id);
    }

    @Override
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.loadById(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.loadById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }
}
